<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @abstract 递4方数据推送接口
 * @author zxj
 */
class PostOrder extends CI_Controller
{
    private $curEnv = '4px_open'; //4px_sandbox 开发环境  4px_open 生产环境
    private $params = array(); //配置参数
    function __construct()
    {
        parent::__construct();
        //加载模型
        $this->load->model('order_model');
        $this->load->model('product_model');
        $this->load->model('brand_model');
        $this->initialize();
    }

    /**
     * 初始化
     */
    public function initialize()
    {
        date_default_timezone_set('PRC');
        $this->load->config('repair_api');
        $this->params = $this->config->item($this->curEnv);
        if(!$this->params){
            json_output('','获取配置失败',false);
        }
        //初始化密钥
        $this->params['secret'] = hexToStr($this->params['secret']);
    }


    /**
     * 推送订单信息
     * @param string $id 订单ID
     * @return bool
     */
    function post_priceList($id = '')
    {
        if (!$id){
            show_error('order ID null');
        }
        $orderFirst = $this->order_model->getOrderData($id);
        //推送的数据
        $pushOrder = $pushProduct = $newProduct = array();
        $pushOrder['maintain_order_id'] = $id;
        $pushOrder['repaire_order_id'] = mt_rand(100000,999999);
        if(!$pushOrder['repaire_order_id']){
            json_output('', '报价单单号不能为空', false);
        }
        $pushOrder['reference_order_number'] = $orderFirst['source_int_id'];
        if(!$pushOrder['reference_order_number']){
            json_output('', '客户单号不能为空', false);
        }
        if($orderFirst['price_type']=='0'){
            $pushOrder['price_type'] = 'A';
        }elseif($orderFirst['price_type']=='1'){
            $pushOrder['price_type'] = 'B';
        }
        $productList = $this->product_model->get_product('', $id);
        foreach ($productList as $row) {
            $brandFirst = $this->brand_model->get_brand($row['brand_id']);
            $newProduct['products_id'] = $row['source_product_id'];
            $newProduct['products_sort'] = $row['sort_id'];
            $newProduct['products_brand_id'] = $row['brand_id'];
            $newProduct['products_brand_name'] = $row['brand_name']?$row['brand_name']:$brandFirst['brand_name'];
            $newProduct['products_model'] = $row['product_model'];
            $newProduct['imei'] = $row['imei'];
            $newProduct['size'] = $row['size'];
            $newProduct['color'] = $row['color'];
            $newProduct['is_bluetooth'] = $row['is_bluetooth'];
            $newProduct['is_remote_control'] = $row['is_yaokong'];
            //查询报价单
            $priceData = $this->product_model->getPriceOne($row['product_id']);
            //$sfwhere = array('site_id'=>$orderFirst['repair_site_id'],'part_id'=>78);
            //$serviceFee = $this->common_model->selectFirst('maintain_item_list',$sfwhere);
            $newProduct['overhaul_price'] = $priceData['overhaulAmount'];  //检测费
            $newProduct['maintain_price'] = $priceData['maintain_price'];
            $newProduct['accessory_price'] = round($priceData['accessory_price']*6.6, 2);
            $newProduct['products_report_id'] = $priceData['id'];
            //查询质检报告
            $qcReportData = $this->product_model->getQcReport($row['product_id']);
            $newProduct['products_report_id'] = (int)$qcReportData['product_price_id'];
            $newProduct['remark'] = $qcReportData['attachment'].$qcReportData['fault'].$priceData['part'];
            $pushProduct[] = $newProduct;
        }
        //gsh_output($pushProduct,1);
        $pushOrder['products_list'] = $pushProduct;
        if(!$pushOrder['products_list'] || !is_array($pushOrder['products_list'])){
            json_output('', '产品不能为空或非数组', false);
        }
        $curlOrder['maintainDetails'][] = $pushOrder;
        $pushOrderStr = addslashes(json_encode($curlOrder));
        $curlParam = "[\"$pushOrderStr\",\"MAINTAIN_ORDER_BID\"]";
        //生成超时毫秒数 10秒
        $expired = getMillisecond()+10000;
        //生成requestID
        $requestId = md5(uniqid());
        //拼接签名字符串
        $sigArr = array(
            'appKey'=>$this->params['appKey'],
            'method'=>$this->params['method'],
            'params'=>$curlParam,
            'requestId'=>$requestId,
            'service'=>$this->params['service'],
        );
        $sigStr = '';
        foreach ($sigArr as $key=>$val) {
            $sigStr .= "$key=".$val.';';
        }
        $sigVal = hash_hmac('md5', $sigStr, $this->params['secret']);

        //拼接连接
        $postFieldsArr = array(
            'service'=>$this->params['service'],
            'method'=>$this->params['method'],
            'requestId'=>$requestId,
            'params'=>$curlParam,
            'appKey'=>$this->params['appKey'],
            'sig'=>$sigVal
        );
        foreach ($postFieldsArr as $key=>$val) {
            $vals[] = $key."=".urlencode($val);
        }
        //$postFields = implode('&',$vals);
        /*
        gsh_output($pushOrder);
        gsh_output($curlParam);
        gsh_output($postFieldsArr,1);
        */
        $postFields =  http_build_query($postFieldsArr);
        $url =  $this->params['url'].$postFields;
        $rsCurlStr = $this->vget($url);
        echo $rsCurlStr;
    }


    /**
     * 推送维修完成信息
     * @param string $id 订单ID
     * @return bool
     */
    function post_repairFinish($id = '')
    {
        if (!$id){
            show_error('order ID null');
        }
        $orderFirst = $this->order_model->getOrderData($id);
        //推送的数据
        $pushOrder = $pushProduct = $newProduct = array();
        $pushOrder['maintain_order_id'] = $id;
        $pushOrder['reference_order_number'] = $orderFirst['source_int_id'];
        $pushOrder['maintain_finished_datetime'] = time('Y-m-d H:i:s');
        $pushOrder['finished_status'] = 'Yes'; //or No
        $curlOrder['maintainDetails'][] = $pushOrder;
        $pushOrderStr = addslashes(json_encode($curlOrder));
        $curlParam = "[\"$pushOrderStr\",\"WMS_RMA_MAINTAIN_ORDER_FINISHED\"]";

        //生成超时毫秒数 10秒
        $expired = getMillisecond()+10000;
        //生成requestID
        $requestId = md5(uniqid());
        //拼接签名字符串
        $sigArr = array(
            'appKey'=>$this->params['appKey'],
            'method'=>$this->params['method'],
            'params'=>$curlParam,
            'requestId'=>$requestId,
            'service'=>$this->params['service'],
        );
        $sigStr = '';
        foreach ($sigArr as $key=>$val) {
            $sigStr .= "$key=".$val.';';
        }
        $sigVal = hash_hmac('md5', $sigStr, $this->params['secret']);

        //拼接连接
        $postFieldsArr = array(
            'service'=>$this->params['service'],
            'method'=>$this->params['method'],
            'requestId'=>$requestId,
            'params'=>$curlParam,
            'appKey'=>$this->params['appKey'],
            'sig'=>$sigVal
        );
        foreach ($postFieldsArr as $key=>$val) {
            $vals[] = $key."=".urlencode($val);
        }
        //$postFields = implode('&',$vals);
        $postFields =  http_build_query($postFieldsArr);
        $url =  $this->params['url'].$postFields;

        //curl post
        $rsCurlStr = $this->vget($url);
        echo $rsCurlStr;
    }


    /**
     * 推送质检报告
     * @param string $id
     */
    function post_flow_report($id = '')
    {
        $id = $id ? $id : gp('id');
        $orderRows = $this->common_model->selectFirst('maintain_order', array('maintain_id' => $id));
        $qcRows = $this->common_model->selectFirst('maintain_qcreport', array('oid' => $id));
        if (!$qcRows) {
            show_error('No quality inspection report found');
        }
        $goal_url = 'http://tomrepair.es/~tomrepair/api/sendInspectionReport';
        $data_to_post = array();
        $data_to_post['user'] = 'api@tomrepair.es';
        $data_to_post['token'] = '78de933bd0fbacf02ef2de1116e3338f1c627b07';
        $data_to_post['oid'] = $qcRows['oid'];
        $data_to_post['pid'] = $qcRows['pid'];
        $data_to_post['source_int_id'] = $orderRows['source_int_id'];
        $data_to_post['is_description'] = $qcRows['is_description']; //当is_description=1时，confirm('是否需要维修');
        $data_to_post['description'] = $qcRows['description']; //The new field
        $data_to_post['damage_name'] = $qcRows['damage'];
        $data_to_post['attachment'] = $qcRows['attachment'];
        $data_to_post['fault'] = $qcRows['fault'];
        $data_to_post['add_time'] = $qcRows['add_time']; // int length  10  time()
        $data_to_post['add_user'] = $qcRows['add_user'];
        $data_to_post = json_encode($data_to_post);
        $curlRs = $this->vpost($goal_url,$data_to_post);
        $curlRs = json_decode($curlRs,true);
        $msg = $curlRs['error_code']==100?'推送成功':'推送失败';
        show_goto('orders/order/inDetails/'.$id,$msg);
    }



    /**
     * 推送报价单
     * @param $id
     * @return bool
     */
    function post_flow_price($id = '')
    {
        $id = $id ? $id : gp('id');
        //推送数组
        $data_to_post = array();
        $priceRows = $this->common_model->selectFirst('maintain_product_price', array('oid' => $id));
        if (!$priceRows) {
            show_error('No offer');
        }
        $orderRows = $this->common_model->selectFirst('maintain_order', array('maintain_id' => $id));
        $productRows = $this->common_model->selectFirst('maintain_product',array('maintain_id'=>$orderRows['maintain_id']));
        //推送规则 ->品牌型号判定
        $pushRuleAry = pushRule();
        $brandPush = $pushRuleAry[$productRows['brand_id']];
        //税
        $tax =pushRuleTax($orderRows['repair_site_id']);
        /**
         * 推送数据
        */
        $goal_url = 'http://tomrepair.es/~tomrepair/api/sendQuote';
        $data_to_post['user'] = 'api@tomrepair.es';
        $data_to_post['token'] = '78de933bd0fbacf02ef2de1116e3338f1c627b07';
        $data_to_post['tax'] = $tax;
        $data_to_post['oid'] = $priceRows['oid'];
        $data_to_post['pid'] = $priceRows['pid'];
        $data_to_post['source_int_id'] = $orderRows['source_int_id'];
        //默认推送全部
        $data_to_post['service_fee'] = $priceRows['maintain_price']; // 手工费
        $data_to_post['part_fee'] = $priceRows['accessory_price'];  //配件费
        $data_to_post['shipping_fee'] = $priceRows['freight_price']?$priceRows['freight_price']:$priceRows['shipping_fee'];    //运费
        $data_to_post['discount'] = $orderRows['coupon_money']; //优惠金额
        $data_to_post['additional_fee'] = $orderRows['append_money'];   //额外金额
        $data_to_post['price_if_not_accepted'] = $priceRows['no_accept_price'];   //不接受报价费用
        $data_to_post['partItemText'] = $productRows['part']; //维修项
        $productRows['product_model'] = strtolower($productRows['product_model']);
        //如果保内需要改变费用
        if($productRows['is_guarantee']){
            //if($productRows['product_model'] && $brandPush && in_array($productRows['product_model'],$brandPush)){
                //速卖通保内不推送
                if($orderRows['website_origin']==6){
                    return false;
                }else{
                    //其他保内推送运费 和 检测费用
                    $sfwhere = array('site_id'=>$orderRows['repair_site_id'],'part_id'=>78);
                    $serviceFee = $this->common_model->selectFirst('maintain_item_list',$sfwhere);
                    //$data_to_post['service_fee'] = $serviceFee['open_price']; // 检测费
                    $data_to_post['service_fee'] = 0; // 检测费
                    $data_to_post['part_fee'] = 0;  //配件费
                    $data_to_post['discount'] = 0; //优惠金额
                    $data_to_post['additional_fee'] = 0;   //额外金额
                    $data_to_post['price_if_not_accepted'] = 0;   //不接受报价费用
                }
            //}
        }
        //全部费用
        $totPrice = $data_to_post['service_fee']
            +$data_to_post['part_fee']
            +$data_to_post['shipping_fee']
            +$data_to_post['discount']
            +$data_to_post['additional_fee']
            +$data_to_post['price_if_not_accepted'];

        $data_to_post['totPrice'] = $totPrice;
        //不接受报价费用
        $data_to_post['price_if_not_accpet'] = $totPrice-$data_to_post['part_fee']-$data_to_post['service_fee'];
        //不接受报价税
        $data_to_post['tax_for_not_accepted'] = $data_to_post['price_if_not_accpet']*$tax;
        //不接受报价总价
        $data_to_post['total_for_not_accepted'] = $data_to_post['price_if_not_accpet']+$data_to_post['tax_for_not_accepted'];

        //接受报价费用
        $data_to_post['price_if_accepted'] = $totPrice-$data_to_post['price_if_not_accepted'];
        //接受报价税
        $data_to_post['tax_for_accepted'] = $data_to_post['price_if_accepted']*$tax;
        //接受报价总价
        $data_to_post['total_for_accepted'] = $data_to_post['price_if_accepted']+$data_to_post['tax_for_accepted'];

        $data_to_post['is_accept_price'] = $priceRows['is_accept_price'];  //是否接受报价  0 or 1
        $data_to_post['is_pay'] = $priceRows['is_pay'];  //是否已支付 0 or 1
        //维修项
        $data_to_post['part'] = $productRows['part'];

        $data_to_post['currency_sort'] = $priceRows['price_sort'];  //货币种类
        $data_to_post['add_time'] = $priceRows['add_time']; // int length  10  time()
        $data_to_post['add_user'] = $priceRows['add_user'];
        //gsh_output($data_to_post,1);
        $data_to_post = json_encode($data_to_post);
        $curlRs = $this->vpost($goal_url,$data_to_post);
        $curlRs = json_decode($curlRs,true);
        $msg = $curlRs['error_code']==100?'推送成功':'推送失败';
        show_goto('orders/order/inDetails/'.$id,$msg);
    }



    /**
     * 模拟获取内容函数
     * @param $url
     * @param array $header
     * @return mixed
     */
    function vget($url,$header = array()){
        $curl = curl_init();//启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);//要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);// 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);// 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);// 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_REFERER,'http://erp.tomrepair.es');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);// 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);// 自动设置Referer
        curl_setopt($curl, CURLOPT_HTTPGET, 1);// 发送一个常规的GET请求
        if(count($header) >= 1 ){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);//设置头信息的地方
        }
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);// 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0);// 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($curl, CURLOPT_SSLCERT, FCPATH . $this->params['cert_url']);
        curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $this->params['cert_pwd']);
        curl_setopt($curl, CURLOPT_SSLKEY, FCPATH . $this->params['cert_key']);
        $tmpInfo = curl_exec($curl);// 执行操作
        if (curl_errno($curl)){
            echo 'Errno'.curl_error($curl);
        }
        curl_close($curl);// 关闭CURL会话
        return $tmpInfo;// 返回数据
    }



    function vpost($url,$pushData,$header = array())
    {
        $header[] = 'Authorization: DMCOHh3Y6Zf562MaDU3YzMyRjp3RFP9987trzdLZRZzcjFt';
        $header[] = 'Content-Type: application/json; charset=utf-8';
        $curl = curl_init();//启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);//要访问的地址
        if (count($header) >= 1) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);//设置头信息的地方
        }
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);// 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0);// 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $pushData);
        $tmpInfo = curl_exec($curl);// 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl);
        return $tmpInfo;
    }


}
